#pragma once
#include<Arduino.h>
#include<ESP8266WiFi.h>
#include<ESP8266HTTPClient.h>
#include"string_ext.hpp"

namespace ganix{
    namespace http
    {
        WiFiClient _wifi_client;
        HTTPClient _http_client;

        int get(const String request, String & response, int timeout = 100) {
            //Serial.println("request: " + request);
            _http_client.setTimeout(timeout);
            _http_client.begin(_wifi_client, request);
            int ret_code = _http_client.GET();
            if (ret_code > 0) {
                if (ret_code == HTTP_CODE_OK) {
                    response = _http_client.getString();
                }
            } else {
                Serial.printf("request(%s) failed(%d), cause : %s\n", request.c_str(), ret_code, _http_client.errorToString(ret_code).c_str());
            }
            _http_client.end();
            return ret_code;
        }

        int get(const String request, String & response, const String keys[], const String values[], int count, int timeout = 100) {
            String param = "";
            if (count > 0) {
                param += '?';
                for (int i=0; i<count; i++) {
                    param += string_ext::url_encode(keys[i]) + "=" + string_ext::url_encode(values[i]);
                    if (i < count-1) {
                        param += '&';
                    }
                }
            }
            return get(request + param, response, timeout);
        }

        int post_json(const String request, String & response, const String json, int timeout = 100) {
            _http_client.setTimeout(timeout);
            _http_client.begin(_wifi_client, request);
            _http_client.addHeader("Content-Type", "application/json");
            int ret_code = _http_client.POST(json);
            if (ret_code > 0) {
                if (ret_code == HTTP_CODE_OK) {
                    response = _http_client.getString();
                }
            } else {
                Serial.printf("http failed, cause : %s\n", _http_client.errorToString(ret_code).c_str());
            }
            _http_client.end();
            return ret_code;
        }
    } // namespace http
} // namespace gani

